package comms;

import javax.microedition.io.SocketConnection;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;

public class SocketAgentConnectionHandler extends Thread {
	private ConnectionManager manager;
	private SocketConnection currentConnection;
	private InputStream inStream;
	private OutputStream outStream;
	private boolean listening;
	private boolean agentReceived;

	public SocketAgentConnectionHandler(ConnectionManager manager, SocketConnection connection) {
		this.manager = manager;
		this.currentConnection = connection;
		this.listening = true;
		this.agentReceived = false;
		try {
			this.inStream = connection.openInputStream();
			this.outStream = connection.openOutputStream();
		} catch (IOException e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
		}
		
		this.start();
	}
	
	//TODO: probably requires a more robust protocol for comms.
	public void run() {
		StringBuffer buff = new StringBuffer(0);
		int streamChar = 0;
		
		try {
			while (this.listening && !this.agentReceived) {
				
				streamChar = this.inStream.read();
				while (streamChar != -1) {
					buff.append((char)streamChar);
					System.err.println("char: " + (char)streamChar);
					streamChar = this.inStream.read();
				}
				System.err.println("Exited while loop char is: " + streamChar);
							
				if (streamChar == -1) {
					System.err.println("End of Stream");
/*CHANGE MADE HERE*/					this.agentReceived = true;
					break;
				}
			}
		} catch (IOException e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
		}
		System.err.println("connectionhandler finish");
		this.manager.agentReceived(buff.toString().getBytes(), buff.length());
	}
	
	public void close() {
		this.listening = false;
		
		try {
			if (this.inStream != null) this.inStream.close();
			if (this.outStream != null) this.outStream.close();
			this.currentConnection.close();
		} catch (IOException e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
		}
	}
}
